<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" @submit.prevent>
        <el-form-item label="任务名称" prop="name">
          <el-input placeholder="请输入任务名称" v-model="searchParams.title" clearable style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['plugin:colecron:cron:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        v-adaptive
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" prop="id" width="120px" align="center" type="index"></el-table-column>
        <el-table-column label="任务名称" prop="title" width="120px" :show-overflow-tooltip="true" align="center">
        </el-table-column>
        <el-table-column label="任务类型" prop="type" align="center"></el-table-column>
        <el-table-column label="任务执行表达式" prop="rule" align="center" width="100px"></el-table-column>
        <el-table-column label="调用任务字符串" prop="target" align="center" width="200px"> </el-table-column>

        <el-table-column label="任务调用参数" prop="parameter" align="center" width="180px"></el-table-column>
        <el-table-column label="已运行次数" prop="running_times" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column
          label="上次运行时间"
          prop="last_running_time"
          :formatter="dateFormatter"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column label="备注" prop="remark" width="100px" align="center"> </el-table-column>
        <el-table-column label="状态" prop="status" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="启用"
              inactive-text="停止"
              :active-value="1"
              :inactive-value="0"
              :inline-prompt="true"
              @click="handlechangeStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          prop="create_time"
          :formatter="dateFormatter"
          width="100px"
          align="center"
        ></el-table-column>
        <el-table-column label="修改时间" prop="update_time" :formatter="dateFormatter" width="100px" align="center">
        </el-table-column>
        <el-table-column label="是否单次执行" prop="singleton" width="100px" align="center"> </el-table-column>

        <el-table-column label="操作" align="left" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" plain @click="handleUpdate(row)" v-auth="['plugin:colecron:cron:update']">
              修改
            </el-button>

            <el-button type="danger" size="small" plain @click="handleOpenLog(row)" v-auth="['plugin:colecron:cron:open_log']">
              日志
            </el-button>

            <el-button type="danger" size="small" plain @click="handleReload(row)" v-auth="['plugin:colecron:cron:reload']">
              重启任务
            </el-button>

            <el-button type="danger" size="small" plain @click="handleDelete(row)" v-auth="['plugin:colecron:cron:delete']">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDialog
        ref="koiDialogRef"
        :title="title"
        :height="650"
        :width="600"
        @koi-confirm="handleConfirm"
        @koi-cancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="120px" status-icon>
            <el-form-item label="任务名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入任务名称" clearable style="width: 300px" />
            </el-form-item>
            <el-form-item label="任务类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1">命令</el-radio>
                <el-radio :label="2">类模式</el-radio>
                <el-radio :label="3">URL</el-radio>
                <el-radio :label="4">eval</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="cron表达式" prop="rule">
              <el-input v-model="form.rule" placeholder="请输入cron表达式 如:*/30 * * * * *" clearable style="width: 300px" />
            </el-form-item>
            <el-form-item label="调用任务字符串" prop="target">
              <el-input v-model="form.target" placeholder="请输入调用任务字符串" clearable style="width: 300px" />
            </el-form-item>

            <el-form-item label="任务调用参数" prop="parameter">
              <el-input
                v-model="form.parameter"
                type="textarea"
                :rows="3"
                placeholder="请输入任务调用参数 json格式"
                clearable
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入任务调用参数 json格式" clearable style="width: 300px" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                active-text="启用"
                inactive-text="停止"
                :active-value="1"
                :inactive-value="0"
                :inline-prompt="true"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :rows="3" type="textarea" placeholder="请输入备注" style="width: 300px" />
            </el-form-item>
          </el-form>
        </template>
      </KoiDialog>

      <!-- 执行日志 -->
      <KoiDrawer
        ref="recordDrawerRef"
        title="执行日志"
        footer-hidden="true"
        size="1080"
        :loading="confirmLoading"
        cancel-text="关闭"
      >
        <template #content>
          <el-table v-loading="loading" v-adaptive border :data="recordTableList" empty-text="暂时没有数据哟">
            <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
            <el-table-column label="执行目标字符串" prop="target" width="310px" align="center"></el-table-column>
            <el-table-column
              label="任务调用参数"
              prop="parameter"
              width="120px"
              align="center"
              :show-overflow-tooltip="true"
            ></el-table-column>

            <el-table-column label="任务执行异常信息" prop="exception" width="150px" align="center" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="执行状态" prop="return_code" width="150px" align="center" :show-overflow-tooltip="true">
              <template #default="scope">
                {{ scope.row.return_code == 0 ? "成功" : "失败" }}
              </template>
            </el-table-column>
            <el-table-column label="执行所用时间" prop="running_time" width="150px" align="center" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
              label="创建时间"
              prop="create_time"
              :formatter="dateFormatter"
              width="150px"
              align="center"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </el-table>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="coleAppVersionPage">
import { ref, reactive, onMounted } from "vue";
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox } from "@/utils/koi.ts";
import { listPage, read, add, update, changeStatus, remove, cronLog, reload } from "@/plugin/colecron/api/cron/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
const recordTableList = ref<any>([]);
const recordDrawerRef = ref<any>(null);
const total = ref<number>(0);

const dateFormatter = (_row: any, _column: any, cellValue: any) => {
  const date = new Date(cellValue * 1000);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const min = date.getMinutes();
  const sec = date.getSeconds();
  return `${year}-${month}-${day} ${hour}:${min}:${sec}`; // 格式化为YYYY-MM-DD
};

// 查询参数
const searchParams = ref({
  pageNo: 1,
  pageSize: 10,
  title: ""
});

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    title: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

const handlechangeStatus = (row: any) => {
  let text = row.status == "0" ? "停止" : "启用";
  koiMsgBox("确定要把[" + row.title + "]的状态修改为[" + text + "]吗?")
    .then(async () => {
      try {
        await changeStatus(row.id, row.status);
        koiNoticeSuccess("操作成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        handleTableData();
      }
    })
    .catch(() => {
      // koiMsgError("已取消");
    });
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.data;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    console.log("表格数据->>>>>>>>>>>>>>>", res.data);
    tableList.value = res.data.data;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
});
const ids = ref([]); // 选中数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  ids.value = selection.map((item: any) => item.roleId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  koiDialogRef.value.koiOpen();
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await read(id);
    form.value.apk_url = { name: "apk", url: res.data.apk_url };
    form.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据获取失败，请刷新重试");
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  if (row.id == null || row.id == "") {
    koiMsgError("请选择需要修改的数据");
  }
  // 回显数据
  handleEcho(row.id);
  koiDialogRef.value.koiOpen();
};

/** 添加 AND 修改弹出框 */
const koiDialogRef = ref();
// 标题
const title = ref("APP版本");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  title: "",
  type: "",
  rule: "",
  target: "",
  parameter: "",
  status: 1,
  sort: 0,
  remark: ""
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    title: "",
    type: "",
    rule: "",
    target: "",
    parameter: "",
    status: 1,
    sort: 0,
    remark: ""
  };
};

/** 表单规则 */
const rules = reactive({
  system_key: [{ required: true, message: "请选择系统", trigger: "null" }],
  app_version: [{ required: true, message: "请输入版本号", trigger: "null" }],
  regular_update: [{ required: true, message: "请选择发布时间", trigger: "null" }],
  app_version_key: [{ required: true, message: "请输入版本标识", trigger: "null" }],
  apk_url: [{ required: true, message: "请输入更新地址", trigger: "null" }]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        if (form.value.id != null && form.value.id != "") {
          await update(form.value);
        } else {
          await add(form.value);
        }
        koiNoticeSuccess("操作成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("操作成功，请刷新重试");
      } finally {
        confirmLoading.value = false;
        koiDialogRef.value.koiQuickClose();
        resetForm();
        handleListPage();
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  koiMsgBox("您确认需要重新加载任务[" + row.title + "]么？")
    .then(async () => {
      try {
        await remove(row.id);
        koiNoticeSuccess("操作成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        handleTableData();
      }
    })
    .catch(() => {
      // koiMsgError("已取消");
    });
};
/** 重启日志 */
const handleReload = (row: any) => {
  if (row.id == null || row.id == "") {
    koiMsgWarning("请选中需要删除的数据");
  }
  koiMsgBox("您确认需要删除[" + row.title + "]么？")
    .then(async () => {
      try {
        await reload(row.id);
        koiNoticeSuccess("删除成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("删除失败，请刷新重试");
      } finally {
        handleTableData();
      }
    })
    .catch(() => {
      // koiMsgError("已取消");
    });
};

const handleOpenLog = (row: any) => {
  recordDrawerRef.value.koiOpen();
  recordListPage(row.id);
};

const recordListPage = async (id: any) => {
  try {
    loading.value = true;
    recordTableList.value = [];
    const res: any = await cronLog({ crontab_id: id });
    recordTableList.value = res.data.data;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};
</script>

<style lang="scss" scoped></style>
